package com.geekydoo;

import java.util.Scanner;

/**
 * The purpose of this class is to print messages to the console as well as to
 * prompt the user for input on behalf of other classes, thus providing a single
 * class through which all program inputs and outputs travel.
 * 
 * @author Patrick Dutch
 */
public class InputOutputHandler {

	private static Scanner keyboard = new Scanner(System.in);

	// String length at which to wrap lines
	private static final int LINE_WRAP_THRESHOLD = 70;

	/**
	 * This method prints the message argument to standard output, optionally
	 * with a tab preceding the message if the tabPrefix argument is set to
	 * true. Messages are also optionally line-wrapped at 80 characters.
	 * 
	 * @param message The message to print
	 * @param tabPrefix Whether a tab should precede the printed message
	 * @param wrapLines Whether lines greater than 80 characters long should be
	 *            wrapped to a new line
	 */
	public static void printToConsole(String message, boolean tabPrefix, boolean wrapLines) {
		assert (message != null);
		String messageToPrint = message;

		if (wrapLines) {
			int messageSegmentLength;
			do {
				messageSegmentLength = messageToPrint.length();
				if (tabPrefix) {
					messageToPrint = "\t" + messageToPrint;
				}
				if (messageSegmentLength < LINE_WRAP_THRESHOLD) {
					System.out.println(messageToPrint);
				}
				else {
					System.out.println(messageToPrint.substring(0, LINE_WRAP_THRESHOLD));
					messageToPrint = messageToPrint.substring(LINE_WRAP_THRESHOLD);
				}
			}
			while (messageSegmentLength >= 80);
		}
		else {
			if (tabPrefix) {
				messageToPrint = "\t" + messageToPrint;
			}
			System.out.println(messageToPrint);
		}
	}

	/**
	 * This method prints the prompt argument to standard output, optionally
	 * with a tab preceding the prompt if the tabPrefix argument is set to true.
	 * The next line typed by the user is then stored, trimmed of leading and
	 * trailing spaces, and returned. Note that unlike the printToConsole
	 * method, this method does not print a new line after displaying
	 * information to the user.
	 * 
	 * @param prompt The prompt to print
	 * @param tabPrefix Whether a tab should precede the printed prompt
	 * @return The string input by the user through standard input
	 */
	public static String getInputFromConsole(String prompt, boolean tabPrefix) {
		String promptToPrint = prompt;
		if (tabPrefix) {
			promptToPrint = "\t" + promptToPrint;
		}
		System.out.print(promptToPrint);

		String userInput = keyboard.nextLine().trim();
		return userInput;

	}

}
